package com.yt.sys.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import java.util.Date;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.sys.mapper.SysPermissionMapper;
import com.yt.sys.models.service.ISysPermissionService;
import com.yt.sys.models.bo.SysPermissionSaveBO;
import com.yt.sys.models.dto.SysPermissionDTO;
import com.yt.common.exception.BusinessException;
import com.yt.common.enums.CodeEnum;
import com.yt.product.common.config.YmlConfig;
import com.yt.common.utils.StrUtils;

@DubboService
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermissionDTO> implements ISysPermissionService{

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(SysPermissionSaveBO saveBO) {
        // 1. 参数校验
        validatePermissionSaveBO(saveBO);

        // 2. BO转换为DTO
        SysPermissionDTO dto = new SysPermissionDTO();
        BeanUtils.copyProperties(saveBO, dto);

        // 3. 设置默认值
        setPermissionDefaultValues(dto);

        // 4. 生成并设置主键ID
        Long id = ymlConfig.getPkId();
        dto.setId(id);

        // 5. 插入数据库
        return this.insert(dto);
    }

    /**
     * 权限信息参数校验
     */
    private void validatePermissionSaveBO(SysPermissionSaveBO saveBO) {
        if (saveBO == null) {
            throw new BusinessException(CodeEnum.FAIL_100001.getCode(), "权限信息不能为空");
        }
        if (StrUtils.isEmpty(saveBO.getPermissionName())) {
            throw new BusinessException(CodeEnum.FAIL_100002.getCode(), "权限名称不能为空");
        }
        if (StrUtils.isEmpty(saveBO.getPermissionCode())) {
            throw new BusinessException(CodeEnum.FAIL_100003.getCode(), "权限编码不能为空");
        }
        if (saveBO.getType() == null || !(saveBO.getType() >= 1 && saveBO.getType() <= 3)) {
            throw new BusinessException(CodeEnum.FAIL_100004.getCode(), "权限类型必须为1（菜单）、2（按钮）或3（接口）");
        }
        if (StrUtils.isEmpty(saveBO.getUrl())) {
            throw new BusinessException(CodeEnum.FAIL_100005.getCode(), "权限资源路径不能为空");
        }
        if (saveBO.getStatus() == null || (saveBO.getStatus() != 0 && saveBO.getStatus() != 1)) {
            throw new BusinessException(CodeEnum.FAIL_100006.getCode(), "权限状态必须为0（禁用）或1（启用）");
        }
    }

    /**
     * 设置权限信息默认值
     */
    private void setPermissionDefaultValues(SysPermissionDTO dto) {
        // 乐观锁版本号默认0
        dto.setRevision(dto.getRevision() != null ? dto.getRevision() : 0);

        // 创建时间和更新时间默认当前时间
        Date now = new Date();
        dto.setCreateTime(dto.getCreateTime() != null ? dto.getCreateTime() : now);
        dto.setUpdateTime(dto.getUpdateTime() != null ? dto.getUpdateTime() : now);
    }
}